//序列化序号 API
import qs from 'qs';


const App = {
  data() {
    return {
      /**
       *   {
       *     "id": 1,
       *     "question": "1 + 1 = ?",
       *     "items": ["2", "5", "4", "3"],
       *     "answer": 0
       *   },
       */

      order: 0,
      questionData: {},
      myAnswer: -1,
      myResults: []
    }
  },
  template: `
    <div>
      <div v-if="myResults.length > 0">
        <h1>考试结果</h1>
        <ul>
          <li
            v-for="(item, index) of myResults"
            :key="item.qid"
          >
            <h2>题目{{item.qid}}:</h2>
            <p>题目:{{item.question}}</p>
            <p>你的答案：{{item.myAnswer}}</p>
            <p>正确答案：{{item.rightAnswer}}</p>
            <p>正确：{{isRightText(item.isRight)}}</p>
          </li>
        </ul>
      </div>
      <div v-else>
        <h1>编号{{questionData.id}}:</h1>
        <p>{{questionData.question}}</p>
        <div>
          <button
            v-for="(item, index) of questionData.items"
            :key="item"
            @click="selectAnswer(index)"
          >{{item}}</button>
        </div>
      </div>
    </div>
  `,
  //组件挂载完毕后
  mounted() {
    this.getQuestion(this.order);
  },
  watch: {
    //监听order变化
    order(newOrder, oldOrder) {
      this.uploadAnswer(oldOrder, this.myAnswer);
      this.getQuestion(newOrder);
    }
  },
  computed: {
    //计算v-for里的item的逻辑
    isRightText() {
      return function (isRight) {
        return isRight ? '是' : '否';
      }
    }
  },
  methods: {
    getQuestion(order) {
      //qs.stringify({order}) 序列号API
      axios.post('http://localhost:8888/getQuestion', qs.stringify({
          order
        }))
        .then(res => {
          // console.log(res);
          const result = res.data;
          if (res.data.errorCode) {
            this.myResults = result.data;
            return;
          }

          this.questionData = result.data;
        })

      /**
       *  请求成功的数据
       *  {
       *     data:{errorCode: 0, msg: "ok", data: {id: 1, question: "1 + 1 = ?", items: ["2", "5", "4", "3"]}}，
       *     status: 200，
       *     statusText: "OK"
       *  }
       */
    },
    //点击对应按钮保存该按钮答案的下标
    selectAnswer(index) {
      this.myAnswer = index;
      this.order += 1;
      // console.log(this.myAnswer, this.order);
    },
    //点击数字按钮上传答案
    uploadAnswer(order, myAnswer) {
      axios.post('http://localhost:8888/uploadAnswer', qs.stringify({
          order,
          myAnswer
        }))
        .then(res => {
          // console.log(res.data);
        });
    }
  }
};

const vm = Vue.createApp(App).mount('#app');